<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>商家管理</title>
    <meta name="ctx" th:content="${#httpServletRequest.getContextPath()}"/>
    <link rel="stylesheet" th:href="@{/css/admin/base-v2.css}">
    <link rel="stylesheet" th:href="@{/lib/font-awesome/4.7.0/css/font-awesome.min.css}">
    <link rel="stylesheet" th:href="@{/css/admin/app.css}">
</head>

<body>

<div class="app-page">

    <div class="app-page-content">
        <div class="app-card">
            <div class="app-card-body">
                <div class="app-card-body-con">
                    <!-- 过滤器 -->
                    <form class="filter">
                        <div class="filter-group">
                            <div class="filter-item">
                                <div class="form-item row">
                                    <div class="label"><label>商家名称</label></div>
                                    <div class="body">
                                        <input type="text" placeholder="请输入商家名称查询" name="companyName" th:value="${companyName}">
                                    </div>
                                </div>
                            </div>
                            <div class="filter-item">
                                <div class="form-item row">
                                    <div class="label"><label>手机号</label></div>
                                    <div class="body">
                                        <input type="text" placeholder="请输入手机号查询" name="mobilePhone" th:value="${mobilePhone}">
                                    </div>
                                </div>
                            </div>
                            <div class="filter-item">
                                <button class="z-btn z-primary">查询</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="app-card">
            <div class="app-card-body">
                <div class="app-card-body-con">
                    <div class="z-btn-group">
                        <a data-state="4" th:href="@{/ckCompany/addCompanyForward}" class="j-btn-control z-btn z-default add-dept" data-addDept>新增商家</a>
                        <a data-state="3" id="export-device-detail" class="j-btn-control z-btn z-default edit-dept" data-editDept>导出</a>
                    </div>

                    <table class="z-table">
                        <thead>
                        <th>
                            <input type="checkbox" class="input j-checkbox-all">
                        </th>
                        <th>创建时间</th>
                        <th>商家名称</th>
                        <th>联系人</th>
                        <th>手机号</th>
                        <th>操作</th>
                        </thead>
                        <tbody th:each="resultList : ${result}">
                        <tr th:attr="data-id=${resultList.companyId},data-company-code=${resultList.companyCode}">
                            <td>
                                <input type="checkbox" class="input j-checkbox">
                            </td>
                            <td>
                                <span th:text="${resultList.addTime}"></span>
                            </td>
                            <td>
                                <span th:text="${resultList.companyName}"></span>
                            </td>
                            <td>
                                <span th:text="${resultList.contacts}"></span>
                            </td>
                            <td>
                                <span th:text="${resultList.mobilePhone}"></span>
                            </td>
                            <td class="btn-group">
                                <a onclick="agentOperate(this)" th:attr="data-company-code=${resultList.companyCode},data-company-name=${resultList.companyName}">代运营</a>
                                <a onclick="getCompanyInfoDetail(this)" th:attr="data-id=${resultList.companyId}">详情</a>
                                <a class="upload-excel">上传机器码</a>
                            </td>
                        </tr>
                        </tbody>
                    </table>

                    <!-- 分页 -->
                    <div class="pagination z-pat z-fr">
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 上传机器码Excel文件 -->
    <div class="popup-excel popup-default z-popup z-fixed z-df z-flex-cc z-hide">
        <div class="bg" data-popup-close></div>
        <div class="body">
            <div class="title">上传机器码</div>
            <div class="content">
                <form>
                    <div class="form-item row" style="align-items: flex-start;">
                        <input type="hidden" name="excelCompanyCode" >
                        <div class="label">上传机器码</div>
                        <div class="body">
                            <!-- 上传结果 -->
                            <div class="upload-list-text"></div>
                            <div class="upload upload-file"  data-input-name="excelDeviceCode" data-limit="1"
                                 th:attr="data-url=@{/ckCompany/uploadExcel}" data-fieldname="files" data-upload-success="excelUploadSuccess">
                                <div class="upload-tips">只能上传Excel文件</div>
                                <div class="upload-error"></div>
                                <div class="input-opacity">
                                    <input type="file" class="input" accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
                                    <a class="z-btn z-default"><i class="fa fa-upload"></i> 上传文件</a>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
                <div class="z-btn-group">
                    <a class="btn-submit z-btn z-primary">确定</a>
                    <a class="z-btn z-default" data-popup-close>取消</a>
                </div>
            </div>
        </div>
    </div>

</div>
<script th:src="@{/lib/jquery.min.js}"></script>
<script th:src="@{/lib/layer-v3.1.1/layer/layer.js}"></script>
<script th:src="@{/js/popup.js}"></script>
<script th:src="@{/js/form.js}"></script>
<script th:src="@{/js/admin/app.js}"></script>
<script th:src="@{/js/admin-upload.js}"></script>
<script th:src="@{/js/pagination.js}"></script>
<script>
    //获取context path
    var context = $("meta[name='ctx']").attr("content");

    //处理分页
    var pageNum = [[${pageNum}]];
    var pageSize = [[${pageSize}]];
    var total = [[${total}]];

    var pagination = new Pagination(".pagination", {
        pageIndex: pageNum, // 当前页数
        pageSize: pageSize, // 每页数量
        count: total, // 总条数
        maxButtonCount: 5, // 分页按钮数量(可选)
        // 分页切换事件
        onPageChanged: function(pageIndex) {
            var paramStr = createParamStr();
            window.location.href = "/ckips/ckCompany/listByPage?pageNum=" + pageIndex + "&pageSize=" + pageSize + paramStr;
        }
    })

    // 加载select联动内容
    $('[name="searchType"] option').each(function (index, element) {
        if ((App.query.searchType === undefined && index === 0) || App.query.searchType == $(this).val()) {
            $('.j-option-switch .content').html($(".search").children('div').eq(index).html())
        }
    })

    // 从URL加载搜索数据
    $(".filter").formLoad(App.query);

    // 后台渲染分页 - 补全url参数(后台传参可以忽略)
    $(".z-page a").each(function () {
        $(this).attr("href", $(this).attr("href") + location.search)
    });

    // 获取表格中选择的ID
    function getSelecteId() {
        let temp = [];
        $('tbody [type="checkbox"]').each(function (index, element) {
            if (element.checked == true) {
                temp.push($(this).parents('tr,.tr').data('id'));
            }
        })

        return temp.join(',');
    }

    //导出excel
    $('#export-device-detail').click(function () {
        var url = context + "/ckCompany/exportCkCompany";
        var paramStr = createParamStr();
        if(paramStr !== ""){
            paramStr = paramStr.substring(1);
            url = url + "?" + paramStr;
        }
        window.location.href = url;
    });

    /**
     * 创建参数字符串
     * @param pageIndex 当前页
     * @param pageSize 每页条数
     * @returns {string} 参数字符串
     */
    function createParamStr() {
        var companyName = $("input[name='companyName']").val();
        var mobilePhone = $("input[name='mobilePhone']").val();
        var url = "";
        if(!isBlank(companyName)){
            url = url + "&companyName=" + companyName;
        }
        if(!isBlank(mobilePhone)){
            url = url + "&mobilePhone=" + mobilePhone;
        }
        return url;
    }

    //检查参数
    function isBlank(param) {
        if(undefined === param){
            return true;
        }
        if(null == param){
            return true;
        }
        if("" === param){
            return true;
        }
        return false;
    }

    // 打开商家详情页
    function getCompanyInfoDetail(item) {
        var data = item.dataset;
        var companyId = data.id;
        if(companyId == null || "" == companyId) {
            popup.tipsTop("商家信息错误，请刷新后重试", 'warning');
            return ;
        }else {
            window.location.href = context + "/ckCompany/getCompanyInfoDetail?companyId=" + companyId;
        }
    }

    // 代运营
    function agentOperate(item) {
        var data = item.dataset;
        var companyCode = data.companyCode;
        var companyName = data.companyName;
        if(companyCode == null || "" == companyCode) {
            popup.tipsTop("商家信息错误，请刷新后重试", 'warning');
            return ;
        }else {
            $.ajax({
                type: "POST",
                url: context + "/ckCompany/agentOperate",
                data: {
                    companyCode:companyCode,
                    companyName:companyName},
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        if(parent)
                            parent.location.href = context + "/web/goIndex";
                    } else {
                        alert(obj.msg);
                    }
                }
            })
        }
    }

    // 上传机器码 - 弹窗打开
    $('.upload-excel').click(function () {
        var data = $(this).parents('tr')[0].dataset;
        console.log('上传机器码');
        console.log('data', data);
        popup.open('.popup-excel');

        $('.popup-excel').formLoad({
            excelCompanyCode:data.companyCode,
        })
    })

    // 上传机器码Excel文件
    var form = $(".popup-excel form").form({
        submitSelector: ".btn-submit",
        msg: function(msg) {
            popup.tipsTop(msg, 'warning');
        },
        submit: function() {
            var data = {};
            $.each($(".popup-excel form").serializeArray(), function(index, field) {
                if (data[field.name]) {
                    data[field.name] += "," + field.value;
                } else {
                    data[field.name] = field.value;
                }
            })
            console.log("excel");
            console.log(data);

            $.ajax({
                type:"POST",
                url :context + "/ckCompany/updateDeviceCode",
                data:data,
                success: function(obj) {
                    console.log(obj);
                    var code = obj.code;
                    if (code == 0) {
                        alert(obj.msg);
                        window.location.href = context + "/ckCompany/listByPage";
                    } else {
                        alert(obj.msg);
                    }
                }
            })
        }
    })

    /**
     * 上传机器码文件回调函数
     * @param result
     */
    function excelUploadSuccess(result) {
        $('.upload-list-text').html("<div class=\"upload-item\" data-id=\"0\"> <input type=\"text\" name=\"excelDeviceCode\" class=\"z-hide\" value='"+result+"'> <div class=\"head\"> <a class=\"name\" target=\"_blank\">" + "上传成功" + "</a> <div class=\"close fa fa-close\"></div> </div> </div>")
    }
</script>
</body>

</html>